//
//  MyTopicViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/4/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import MJRefresh
import UITableView_FDTemplateLayoutCell
import SVProgressHUD
import AVOSCloud

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}


class MyTopicViewController: RootViewController,UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tabView: UITableView!
    
    var topicArray = [Topic]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的主贴"
        tabView.tableFooterView = UIView()
        self.tabView.register(UINib(nibName: "MainPageTopicsCell", bundle: nil), forCellReuseIdentifier: "MainPageTopicsCell")
        
        self.tabView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.requestData(true)
        })
        
        self.tabView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.requestData(false)
        })
        requestData(true)
    }
    
    // MARK: netRequest
    
    func requestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Topic.query()
        query.includeKey(kTopicKeyContentImage)
        query.includeKey(kTopicKeyUser)
        query.includeKey(kTopicKeyCitys)
        query.order(byDescending: "createdAt")        // 创建时间排序
        query.whereKey(kTopicKeyUser, equalTo: AVUser.current())
        query.limit = kNetPageSize
        
        if !header {
            let top = topicArray.last
            let date = top?.object(forKey: "createdAt")
            if date != nil {
                query.whereKey("createdAt", lessThan: date)
            } else {
                query.whereKey("createdAt", lessThan: Date())
            }
        }
        
        query.findObjectsInBackground { (objects:[Any]?, error:Error?) in
            self.resolveObject(objects, error: error, header: header)
        }
        
//        query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) in
//            self.resolveObject(objects, error: error, header: header)
//        }
    }
    
    func resolveObject(_ objects: [Any]?, error: Error?, header: Bool) {
        if error == nil && objects != nil {
            if let topic = objects as? [Topic] {
                if header {
                    self.topicArray.removeAll()
                }
                self.topicArray += topic
                self.tabView.reloadData()
                SVProgressHUD.dismiss()
            } else {
                SVProgressHUD.showError(withStatus: "获取列表失败")
            }
        } else {
            SVProgressHUD.showError(withStatus: error?.localizedDescription)
        }
        self.tabView.mj_header.endRefreshing()
        if objects != nil && objects?.count < kNetPageSize {
            self.tabView.mj_footer.endRefreshingWithNoMoreData()
        } else {
            if header {
                self.tabView.mj_footer.resetNoMoreData()
            } else {
                self.tabView.mj_footer.endRefreshing()
            }
        }
    }

    // MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return topicArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: "MainPageTopicsCell", configuration: { (cell: Any?) in
            let mainCell = cell as? MainPageTopicsCell
            let topic = self.topicArray[(indexPath as NSIndexPath).row]
            mainCell?.refreshView(topic)
        })
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MainPageTopicsCell", for: indexPath) as! MainPageTopicsCell
        cell.selectionStyle = .none
        let topic = topicArray[(indexPath as NSIndexPath).row]
        cell.refreshView(topic)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let topic = topicArray[(indexPath as NSIndexPath).row]
        let cirDetailVC = UIStoryboard.mainStoryboard.instantiateViewController(withIdentifier: "CirclReplyViewController") as! CirclReplyViewController;
        cirDetailVC.topic = topic
        cirDetailVC.city = topic.city
        self.navigationController?.pushViewController(cirDetailVC, animated: true)
    }

}
